use good_mitm_passive_scan_simple::{HttpEvent, PassiveScanEngine, Severity};
use std::collections::HashMap;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // 初始化日志
    env_logger::init();
    
    println!("🔍 测试Good-MITM被动扫描引擎 - 触发告警");
    
    // 创建扫描引擎
    let scan_engine = PassiveScanEngine::new();
    println!("✅ 被动扫描引擎创建成功");
    
    // 等待规则加载完成
    tokio::time::sleep(tokio::time::Duration::from_millis(100)).await;
    
    // 测试用例1: 密码泄露检测 - 高优先级告警
    println!("\n🔴 测试1: 密码泄露检测 (高优先级告警)");
    let mut headers1 = HashMap::new();
    headers1.insert("content-type".to_string(), "application/json".to_string());
    
    let password_event = HttpEvent::new_response(
        200,
        headers1,
        r#"{"user": "admin", "password": "secret123456"}"#.to_string(),
        "https://example.com/api/login".to_string(),
        "POST".to_string(),
    );
    
    let results1 = scan_engine.process_event(password_event).await?;
    print_scan_results("密码泄露检测", &results1);
    
    // 测试用例2: API密钥泄露 - 高优先级告警
    println!("\n🔴 测试2: API密钥泄露检测 (高优先级告警)");
    let mut headers2 = HashMap::new();
    headers2.insert("content-type".to_string(), "application/json".to_string());
    
    let api_key_event = HttpEvent::new_response(
        200,
        headers2,
        r#"{"api_key": "sk_live_1234567890abcdef1234567890abcdef", "user": "test_user"}"#.to_string(),
        "https://api.example.com/config".to_string(),
        "GET".to_string(),
    );
    
    let results2 = scan_engine.process_event(api_key_event).await?;
    print_scan_results("API密钥泄露检测", &results2);
    
    // 测试用例3: SQL错误信息 - 中优先级告警
    println!("\n🟡 测试3: SQL错误信息检测 (中优先级告警)");
    let mut headers3 = HashMap::new();
    headers3.insert("content-type".to_string(), "text/html".to_string());
    
    let sql_error_event = HttpEvent::new_response(
        500,
        headers3,
        r#"<html><body>Error: SQL syntax error near 'SELECT * FROM users WHERE id=' OR 1=1' at line 1</body></html>"#.to_string(),
        "https://example.com/search".to_string(),
        "GET".to_string(),
    );
    
    let results3 = scan_engine.process_event(sql_error_event).await?;
    print_scan_results("SQL错误信息检测", &results3);
    
    // 测试用例4: 数据库连接字符串 - 严重告警
    println!("\n🔴 测试4: 数据库连接字符串泄露 (严重告警)");
    let mut headers4 = HashMap::new();
    headers4.insert("content-type".to_string(), "text/plain".to_string());
    
    let db_conn_event = HttpEvent::new_response(
        200,
        headers4,
        r#"Connection string: mysql://admin:password123@localhost:3306/user_db"#.to_string(),
        "https://example.com/config.txt".to_string(),
        "GET".to_string(),
    );
    
    let results4 = scan_engine.process_event(db_conn_event).await?;
    print_scan_results("数据库连接字符串泄露检测", &results4);
    
    // 测试用例5: JWT Token泄露 - 中优先级告警
    println!("\n🟡 测试5: JWT Token泄露检测 (中优先级告警)");
    let mut headers5 = HashMap::new();
    headers5.insert("content-type".to_string(), "application/json".to_string());
    
    let jwt_event = HttpEvent::new_response(
        200,
        headers5,
        r#"{"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOjEsImV4cCI6MTY4ODQyMDQ5N30.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c"}"#.to_string(),
        "https://example.com/auth/refresh".to_string(),
        "POST".to_string(),
    );
    
    let results5 = scan_engine.process_event(jwt_event).await?;
    print_scan_results("JWT Token泄露检测", &results5);
    
    // 获取扫描统计信息
    println!("\n📊 扫描统计信息:");
    let stats = scan_engine.get_stats().await;
    println!("  总问题数: {}", stats.total_results);
    for (severity, count) in stats.results_by_severity {
        println!("  {}: {} 个问题", format!("{:?}", severity), count);
    }
    
    println!("\n✅ 告警测试完成!");
    Ok(())
}

// 辅助函数: 打印扫描结果
fn print_scan_results(test_name: &str, results: &[good_mitm_passive_scan_simple::ScanResult]) {
    if results.is_empty() {
        println!("  ⚠️  {test_name}: 未发现问题 (扫描规则可能未正确识别)");
        return;
    }
    
    println!("  🚨 {test_name}: 发现 {} 个安全问题:", results.len());
    for result in results {
        let severity_icon = match result.severity {
            Severity::Critical => "🔴 严重",
            Severity::High => "🔴 高",
            Severity::Medium => "🟡 中",
            Severity::Low => "🟢 低",
            Severity::Info => "🔵 信息",
        };
        println!("    - {} | {} | {}", severity_icon, result.title, result.url);
        println!("      证据: {}", result.evidence);
        println!("      描述: {}", result.description);
    }
}
